import type { Ref } from 'vue'
import type { Expose as DataFormInst } from './form/types'
import type { NvCrudProps } from './types'
import type { NvFormMode } from '@/form/types'
import type { RowData } from '@/types'
import { ref } from 'vue'

export function useActions(
  props: NvCrudProps,
  form: Ref<RowData>,
  formRef: Ref<DataFormInst | undefined>,
) {
  const formVisible = ref(false)
  const formMode = ref<NvFormMode>('view')

  function rowAdd() {
    formMode.value = 'add'
    form.value = {}
    formRef.value?.openForm()
  }

  function rowView(row: RowData) {
    formMode.value = 'view'
    form.value = { ...row }
    formRef.value?.openForm()
  }

  function rowEdit(row: RowData) {
    formMode.value = 'edit'
    form.value = { ...row }
    formRef.value?.openForm()
  }

  function rowDel(row: RowData) {
    props.onRowDelete?.(row)
  }

  return { formVisible, formMode, rowAdd, rowView, rowEdit, rowDel }
}

export type UseActionsReturn = ReturnType<typeof useActions>
